package com.wwg.threadSort;

import java.util.concurrent.Semaphore;

/**
 * @author: wwg
 * @date: 2022/3/11 17:46
 */

/**
 * Semaphore控制线程顺序执行
 */
public class ThreadSortCountSemaphore {

    /**
     * 用于判断线程一是否执行
     */
    private static final Semaphore semaphore1 = new Semaphore(0);

    /**
     * 用于判断线程二是否执行
     */
    private static final Semaphore semaphore2 = new Semaphore(0);

    public static void main(String[] args) {
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行");
                semaphore1.release();
            }
        }, "t1");

        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore1.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行");
                semaphore2.release();

            }
        }, "t2");

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    semaphore2.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行");
            }
        }, "t3");

        thread3.start();
        thread1.start();
        thread2.start();
    }
}
